<template>
  <div>
    <!-- 面包屑 -->
    <div class="mb-6 text-sm text-gray-500 flex items-center">
      <router-link to="/dashboard" class="hover:text-gray-700">控制台</router-link>
      <i class="fas fa-chevron-right mx-2"></i>
      <span class="text-gray-900 font-medium">统计报表</span>
    </div>

    <!-- 标题与操作 -->
    <div class="flex items-center justify-between mb-6">
      <div>
      <h1 class="text-2xl font-bold text-gray-900">统计报表</h1>
        <p class="text-gray-600 mt-1">数据分析和可视化展示</p>
      </div>
      <div class="flex space-x-3">
        <select v-model="selectedPeriod" @change="handlePeriodChange" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
          <option value="week">近一周</option>
          <option value="month">近一月</option>
          <option value="quarter">近一季度</option>
          <option value="year">近一年</option>
        </select>
        <button @click="handleRefresh" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2">
          <i class="fas fa-sync-alt"></i>
          <span>刷新</span>
        </button>
        <button @click="handleExport" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center space-x-2">
          <i class="fas fa-download"></i>
          <span>导出</span>
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">总任务数</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.taskStats?.total || 0 }}</p>
          </div>
          <div class="bg-blue-100 p-3 rounded-lg">
            <i class="fas fa-tasks text-blue-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">总缺陷数</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.defectStats?.total || 0 }}</p>
          </div>
          <div class="bg-red-100 p-3 rounded-lg">
            <i class="fas fa-exclamation-triangle text-red-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">活跃用户</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.personnelStats?.active_users || 0 }}</p>
          </div>
          <div class="bg-green-100 p-3 rounded-lg">
            <i class="fas fa-users text-green-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">完成率</p>
            <p class="text-3xl font-bold text-gray-900">{{ (statistics.taskStats?.completion_rate || 0).toFixed(1) }}%</p>
          </div>
          <div class="bg-purple-100 p-3 rounded-lg">
            <i class="fas fa-chart-line text-purple-600 text-xl"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 任务趋势图 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">任务完成趋势</h3>
          <div class="flex space-x-2">
            <button @click="switchTaskChart('line')" :class="['px-3 py-1 text-xs rounded', taskChartType === 'line' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-600']">折线图</button>
            <button @click="switchTaskChart('bar')" :class="['px-3 py-1 text-xs rounded', taskChartType === 'bar' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-600']">柱状图</button>
          </div>
        </div>
        <div class="h-64">
          <canvas ref="taskChartRef"></canvas>
        </div>
      </div>

      <!-- 缺陷分布图 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">缺陷等级分布</h3>
          <div class="flex space-x-2">
            <button @click="switchDefectChart('pie')" :class="['px-3 py-1 text-xs rounded', defectChartType === 'pie' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-600']">饼图</button>
            <button @click="switchDefectChart('doughnut')" :class="['px-3 py-1 text-xs rounded', defectChartType === 'doughnut' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-600']">环形图</button>
          </div>
        </div>
        <div class="h-64">
          <canvas ref="defectChartRef"></canvas>
        </div>
      </div>
    </div>
    
    <!-- 人员绩效统计 -->
    <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">
      <h3 class="text-lg font-semibold text-gray-900 mb-4">人员绩效排行</h3>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div v-for="(person, index) in statistics.personnelStats?.performance || []" :key="index" class="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
          <div class="flex items-center space-x-3">
            <div class="w-10 h-10 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold">
              {{ index + 1 }}
            </div>
            <div>
              <p class="font-medium text-gray-900">{{ getUserDisplayName(person) }}</p>
              <p class="text-sm text-gray-500">完成任务: {{ person.tasksCompleted || person.tasks_completed || 0 }}个</p>
            </div>
          </div>
            <div class="text-right">
              <p class="font-semibold text-gray-900 text-lg">{{ (person.completionRate || person.completion_rate || 0).toFixed(1) }}%</p>
              <div class="w-24 bg-gray-200 rounded-full h-2 mt-1">
                <div class="bg-blue-600 h-2 rounded-full transition-all duration-300" :style="{ width: (person.completionRate || person.completion_rate || 0) + '%' }"></div>
              </div>
            </div>
        </div>
      </div>
    </div>

    <!-- 详细统计表格 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="p-6 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-900">详细统计</h3>
          <div class="flex space-x-2">
            <select v-model="selectedView" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
              <option value="tasks">任务统计</option>
              <option value="defects">缺陷统计</option>
              <option value="personnel">人员统计</option>
            </select>
          </div>
        </div>
      </div>
      
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">项目</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">占比</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">趋势</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="item in detailedStats" :key="item.name" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ item.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.count }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.percentage.toFixed(1) }}%</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <i :class="['fas mr-1', item.trend > 0 ? 'fa-arrow-up text-green-500' : item.trend < 0 ? 'fa-arrow-down text-red-500' : 'fa-minus text-gray-400']"></i>
                  <span :class="['text-sm', item.trend > 0 ? 'text-green-500' : item.trend < 0 ? 'text-red-500' : 'text-gray-400']">
                    {{ Math.abs(item.trend).toFixed(1) }}%
                  </span>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 flex items-center space-x-3">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span class="text-gray-600">加载统计数据中...</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Chart, registerables } from 'chart.js'
import { statisticsAPI } from '@/api/modules'

// 注册Chart.js组件
Chart.register(...registerables)

// 用户名到真实姓名的映射
const userNameMap = {
  'inspector01': '张三',
  'inspector02': '李四',
  'inspector03': '王五',
  'inspector04': '赵六',
  'maintainer01': '孙七',
  'maintainer02': '孙十',
  'admin': '系统管理员'
}

// 获取用户显示名称
const getUserDisplayName = (person) => {
  const username = person.name || person.username || person.realName || person.displayName
  return userNameMap[username] || username || '未知用户'
}

// 响应式数据
const loading = ref(false)
const selectedPeriod = ref('month')
const selectedView = ref('tasks')
const taskChartType = ref('line')
const defectChartType = ref('pie')

// 统计数据
const statistics = reactive({
  taskStats: null,
  defectStats: null,
  personnelStats: null
})

// 图表引用
const taskChartRef = ref(null)
const defectChartRef = ref(null)
let taskChart = null
let defectChart = null


// 模拟数据
const mockStatistics = {
  taskStats: {
    total: 156,
    completed: 142,
    pending: 8,
    in_progress: 6,
    completion_rate: 91.0,
    trend: [
      { date: '2025-01-01', count: 5 },
      { date: '2025-01-02', count: 8 },
      { date: '2025-01-03', count: 6 },
      { date: '2025-01-04', count: 12 },
      { date: '2025-01-05', count: 9 },
      { date: '2025-01-06', count: 15 },
      { date: '2025-01-07', count: 11 }
    ]
  },
  defectStats: {
    total: 89,
    by_level: {
      low: 15,
      general: 35,
      serious: 20,
      critical: 10,
      high: 6,
      emergency: 3
    },
    by_type: {
      corrosion: 35,
      leakage: 28,
      foreign_matter: 26
    },
    trend: [
      { date: '2025-01-01', count: 3 },
      { date: '2025-01-02', count: 5 },
      { date: '2025-01-03', count: 2 },
      { date: '2025-01-04', count: 8 },
      { date: '2025-01-05', count: 4 },
      { date: '2025-01-06', count: 6 },
      { date: '2025-01-07', count: 7 }
    ]
  },
  personnelStats: {
    total_users: 25,
    active_users: 22,
    by_role: {
      admin: 3,
      inspector: 15,
      maintainer: 7
    },
    performance: [
      { name: '张三', tasks_completed: 45, completion_rate: 95.8 },
      { name: '李四', tasks_completed: 38, completion_rate: 92.7 },
      { name: '王五', tasks_completed: 35, completion_rate: 89.3 },
      { name: '赵六', tasks_completed: 32, completion_rate: 87.1 },
      { name: '钱七', tasks_completed: 28, completion_rate: 84.6 }
    ]
  }
}


// 计算属性
const detailedStats = computed(() => {
  if (selectedView.value === 'tasks') {
    return [
      { name: '已完成', count: statistics.taskStats?.completed || 0, percentage: ((statistics.taskStats?.completed || 0) / (statistics.taskStats?.total || 1)) * 100, trend: 5.2 },
      { name: '待处理', count: statistics.taskStats?.pending || 0, percentage: ((statistics.taskStats?.pending || 0) / (statistics.taskStats?.total || 1)) * 100, trend: -2.1 },
      { name: '进行中', count: statistics.taskStats?.in_progress || 0, percentage: ((statistics.taskStats?.in_progress || 0) / (statistics.taskStats?.total || 1)) * 100, trend: 1.8 }
    ]
  } else if (selectedView.value === 'defects') {
    return [
      { name: '低危缺陷', count: statistics.defectStats?.by_level?.low || 0, percentage: ((statistics.defectStats?.by_level?.low || 0) / (statistics.defectStats?.total || 1)) * 100, trend: 1.2 },
      { name: '一般缺陷', count: statistics.defectStats?.by_level?.general || 0, percentage: ((statistics.defectStats?.by_level?.general || 0) / (statistics.defectStats?.total || 1)) * 100, trend: 3.5 },
      { name: '严重缺陷', count: statistics.defectStats?.by_level?.serious || 0, percentage: ((statistics.defectStats?.by_level?.serious || 0) / (statistics.defectStats?.total || 1)) * 100, trend: -1.2 },
      { name: '危急缺陷', count: statistics.defectStats?.by_level?.critical || 0, percentage: ((statistics.defectStats?.by_level?.critical || 0) / (statistics.defectStats?.total || 1)) * 100, trend: 0.5 },
      { name: '高危缺陷', count: statistics.defectStats?.by_level?.high || 0, percentage: ((statistics.defectStats?.by_level?.high || 0) / (statistics.defectStats?.total || 1)) * 100, trend: 0.3 },
      { name: '紧急缺陷', count: statistics.defectStats?.by_level?.emergency || 0, percentage: ((statistics.defectStats?.by_level?.emergency || 0) / (statistics.defectStats?.total || 1)) * 100, trend: 0.8 }
    ]
  } else {
    return [
      { name: '系统管理员', count: statistics.personnelStats?.by_role?.admin || 0, percentage: ((statistics.personnelStats?.by_role?.admin || 0) / (statistics.personnelStats?.total_users || 1)) * 100, trend: 0 },
      { name: '巡检员', count: statistics.personnelStats?.by_role?.inspector || 0, percentage: ((statistics.personnelStats?.by_role?.inspector || 0) / (statistics.personnelStats?.total_users || 1)) * 100, trend: 2.3 },
      { name: '维护员', count: statistics.personnelStats?.by_role?.maintainer || 0, percentage: ((statistics.personnelStats?.by_role?.maintainer || 0) / (statistics.personnelStats?.total_users || 1)) * 100, trend: -0.5 }
    ]
  }
})

// 方法
const loadStatistics = async () => {
  try {
    loading.value = true
    
    // 获取综合统计数据
    const dashboardResponse = await statisticsAPI.getDashboardStats({
      period: selectedPeriod.value
    })
    
    if (dashboardResponse.code === 0) {
      const data = dashboardResponse.data
      
      // 映射后端数据到前端期望的格式
      statistics.taskStats = {
        total: data.taskStats?.total || 0,
        completed: data.taskStats?.completed || 0,
        pending: data.taskStats?.pending || 0,
        in_progress: data.taskStats?.inProgress || 0,  // 注意：后端是inProgress，不是in_progress
        completion_rate: data.taskStats?.completionRate || 0,
        trend: data.taskStats?.trend || []
      }
      
      // 映射缺陷等级数据（后端返回的是中文名称，需要转换为英文键）
      const levelMapping = {
        '低危': 'low',
        '一般': 'general',
        '严重': 'serious',
        '危急': 'critical',
        '高危': 'high',
        '紧急': 'emergency'
      }
      
      const mappedByLevel = {}
      if (data.defectStats?.byLevel) {
        Object.entries(data.defectStats.byLevel).forEach(([levelName, count]) => {
          const levelKey = levelMapping[levelName] || levelName.toLowerCase()
          mappedByLevel[levelKey] = count
        })
      }
      
      statistics.defectStats = {
        total: data.defectStats?.total || 0,
        by_level: mappedByLevel,
        by_type: data.defectStats?.byType || {},
        trend: data.defectStats?.trend || []
      }
      
      // 映射人员角色数据（后端返回的是中文角色名称，需要转换为英文键）
      const roleMapping = {
        '系统管理员': 'admin',
        '巡检员': 'inspector',
        '维护员': 'maintainer'
      }
      
      const mappedByRole = {}
      if (data.personnelStats?.byRole) {
        Object.entries(data.personnelStats.byRole).forEach(([roleName, count]) => {
          const roleKey = roleMapping[roleName] || roleName.toLowerCase()
          mappedByRole[roleKey] = count
        })
      }
      
      statistics.personnelStats = {
        total_users: data.personnelStats?.totalUsers || 0,
        active_users: data.personnelStats?.activeUsers || 0,
        by_role: mappedByRole,
        performance: data.personnelStats?.performance || []
      }
    } else {
      throw new Error(dashboardResponse.message || '获取统计数据失败')
    }
    
    // 创建图表
    await nextTick()
    createTaskChart()
    createDefectChart()
    
    ElMessage.success('统计数据加载成功')
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
    
    // 如果API调用失败，使用模拟数据作为备用
    console.log('使用模拟数据作为备用')
    statistics.taskStats = mockStatistics.taskStats
    statistics.defectStats = mockStatistics.defectStats
    statistics.personnelStats = mockStatistics.personnelStats
    
    // 创建图表
    await nextTick()
    createTaskChart()
    createDefectChart()
  } finally {
    loading.value = false
  }
}

const createTaskChart = () => {
  if (taskChart) {
    taskChart.destroy()
  }
  
  const ctx = taskChartRef.value?.getContext('2d')
  if (!ctx) return
  
  const data = statistics.taskStats?.trend || []
  
  taskChart = new Chart(ctx, {
    type: taskChartType.value,
    data: {
      labels: data.map(item => item.date),
      datasets: [{
        label: '任务完成数',
        data: data.map(item => item.count),
        borderColor: 'rgb(59, 130, 246)',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        tension: 0.1
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  })
}

const createDefectChart = () => {
  if (defectChart) {
    defectChart.destroy()
  }
  
  const ctx = defectChartRef.value?.getContext('2d')
  if (!ctx) return
  
  const data = statistics.defectStats?.by_level || {}
  
  // 如果数据为空，使用默认数据
  const chartData = {
    low: data.low || 0,
    general: data.general || 0,
    serious: data.serious || 0,
    critical: data.critical || 0,
    high: data.high || 0,
    emergency: data.emergency || 0
  }
  
  // 如果所有数据都为0，使用示例数据
  if (Object.values(chartData).every(val => val === 0)) {
    chartData.low = 2
    chartData.general = 5
    chartData.serious = 3
    chartData.critical = 2
    chartData.high = 1
    chartData.emergency = 1
  }
  
  defectChart = new Chart(ctx, {
    type: defectChartType.value,
    data: {
      labels: ['低危', '一般', '严重', '危急', '高危', '紧急'],
      datasets: [{
        data: [chartData.low, chartData.general, chartData.serious, chartData.critical, chartData.high, chartData.emergency],
        backgroundColor: [
          'rgba(156, 163, 175, 0.8)',    // 低危 - 灰色
          'rgba(34, 197, 94, 0.8)',      // 一般 - 绿色
          'rgba(251, 191, 36, 0.8)',     // 严重 - 黄色
          'rgba(249, 115, 22, 0.8)',     // 危急 - 橙色
          'rgba(239, 68, 68, 0.8)',      // 高危 - 红色
          'rgba(139, 69, 19, 0.8)'       // 紧急 - 深红色
        ],
        borderColor: [
          'rgb(156, 163, 175)',
          'rgb(34, 197, 94)',
          'rgb(251, 191, 36)',
          'rgb(249, 115, 22)',
          'rgb(239, 68, 68)',
          'rgb(139, 69, 19)'
        ],
        borderWidth: 2
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom'
        }
      }
    }
  })
}

const switchTaskChart = (type) => {
  taskChartType.value = type
  createTaskChart()
}

const switchDefectChart = (type) => {
  defectChartType.value = type
  createDefectChart()
}



const handlePeriodChange = () => {
  loadStatistics()
}

const handleRefresh = () => {
  loadStatistics()
}

const handleExport = async () => {
  try {
    ElMessage.info('正在导出数据...')
    
    const response = await statisticsAPI.exportStatistics({
      type: 'dashboard',
      format: 'excel',
      period: selectedPeriod.value
    })
    
    if (response.code === 0) {
      const data = response.data
      // 创建下载链接
      const link = document.createElement('a')
      link.href = data.downloadUrl
      link.download = data.fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('导出成功')
    } else {
      throw new Error(response.message || '导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 生命周期
onMounted(() => {
  loadStatistics()
})

onUnmounted(() => {
  if (taskChart) {
    taskChart.destroy()
  }
  if (defectChart) {
    defectChart.destroy()
  }
})
</script>

<style scoped>
/* 图表容器样式 */
canvas {
  max-height: 256px;
}
</style>
